import Vue from "vue";
import VueRouter from "vue-router";
import BasicLayout from "@/layout/BasicLayout";
import Login from "@/views/Login.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  {
    path: "/",
    name: "BasicLayout",
    component: BasicLayout,
    children: [
      {
        path: "/search",
        name: "SearchPage",
        component: () =>
          import(/* webpackChunkName: "SearchPage" */ "@/views/SearchPage.vue"),
      },
      {
        // 会匹配所有路径
        path: "*",
        name: "Page404",
        component: () =>
          import(/* webpackChunkName: "Page404" */ "@/views/Page404.vue"),
      },
    ],
  },
  // {
  //   path: "/about",
  //   name: "about",
  //   component: () =>
  //     import(/* webpackChunkName: "about" */ "../views/AboutView.vue"),
  // },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

router.beforeEach((to, from, next) => {
  const isLogin = localStorage.getItem("isLogin");
  if ("Login" === to.name) {
    if (isLogin) {
      // 这里可认为是回强制回到首页
      next({ name: "SearchPage" });
    } else {
      // 继续转入登录页
      next();
    }
  } else if ("Page404" === to.name) {
    // 404路由则允许继续访问
    next();
  }
  if (isLogin) {
    // 已登录，则允许继续访问
    next();
  } else {
    // 未登录，则强制转入登录界面
    next({ name: "Login" });
  }
});

export default router;
